import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:developer' as developer;
import '../models/word.dart';
import '../services/database_service.dart';
import '../utils/word_import_export_util.dart';

class WordImportExportScreen extends StatefulWidget {
  final List<Word>? initialWords;
  
  const WordImportExportScreen({Key? key, this.initialWords}) : super(key: key);

  @override
  _WordImportExportScreenState createState() => _WordImportExportScreenState();
}

class _WordImportExportScreenState extends State<WordImportExportScreen> {
  List<Map<String, dynamic>> _words = [];
  String _statusMessage = '';
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    
    // 如果有初始单词数据，则加载它
    if (widget.initialWords != null && widget.initialWords!.isNotEmpty) {
      _words = widget.initialWords!.map((word) => word.toMap()).toList();
      _statusMessage = '已加载${_words.length}个单词';
    } else {
      _statusMessage = '请选择操作';
    }
  }

  // 创建示例单词数据
  Future<void> _createSampleWords() async {
    final sampleWords = [
      Word(
        word: 'apple',
        translation: '苹果',
        pronunciation: '/ˈæpl/',
        meaning: 'a round fruit with red, yellow, or green skin and firm white flesh',
        example: 'I eat an apple every day.',
        category: '水果',
        difficulty: 1,
      ),
      Word(
        word: 'banana',
        translation: '香蕉',
        pronunciation: '/bəˈnɑːnə/',
        meaning: 'a long curved fruit with a yellow skin and soft sweet flesh',
        example: 'Monkeys love to eat bananas.',
        category: '水果',
        difficulty: 1,
      ),
      Word(
        word: 'computer',
        translation: '电脑',
        pronunciation: '/kəmˈpjuːtər/',
        meaning: 'an electronic device for storing and processing data',
        example: 'I use my computer to write emails.',
        category: '科技',
        difficulty: 2,
      ),
      Word(
        word: 'algorithm',
        translation: '算法',
        pronunciation: '/ˈælɡərɪðəm/',
        meaning: 'a process or set of rules to be followed in calculations or other problem-solving operations',
        example: 'Sorting algorithms are fundamental in computer science.',
        category: '科技',
        difficulty: 3,
      ),
      Word(
        word: 'democracy',
        translation: '民主',
        pronunciation: '/dɪˈmɒkrəsi/',
        meaning: 'a system of government by the whole population or all eligible members of a state',
        example: 'The country has been a democracy since 1945.',
        category: '政治',
        difficulty: 3,
      ),
    ];
    
    setState(() {
      _words = sampleWords.map((word) => word.toMap()).toList();
      _statusMessage = '已创建${sampleWords.length}个示例单词';
    });
    
    // 询问用户是否要保存到数据库
    final shouldSave = await showDialog<bool>(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('保存到数据库', style: TextStyle(fontFamily: 'FangSong')),
          content: const Text('是否将示例单词保存到数据库？', style: TextStyle(fontFamily: 'FangSong')),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(false),
              child: const Text('取消', style: TextStyle(fontFamily: 'FangSong')),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(true),
              child: const Text('确定', style: TextStyle(fontFamily: 'FangSong')),
            ),
          ],
        ),
      ) ?? false;
    
    if (shouldSave) {
      await _saveWordsToDatabase(_words);
    }
  }

  // 导出单词
  Future<void> _exportWords() async {
    try {
      setState(() {
        _isLoading = true;
        _statusMessage = '正在导出单词...';
      });
      
      // 检查当前是否有单词数据
      if (_words.isEmpty) {
        // 如果当前列表为空，则从数据库获取所有单词
        final databaseService = DatabaseService();
        await databaseService.init();
        final allWords = await databaseService.wordRepository.getAllWords();
        
        // 导出单词到CSV文件
        final success = await WordImportExportUtil.exportWordsToCSV(allWords);
        
        setState(() {
          _isLoading = false;
          _statusMessage = success != null ? '成功导出${allWords.length}个单词' : '导出单词失败';
        });
      } else {
        // 使用当前列表的单词数据
        // 将Map转换回Word对象
        final List<Word> wordsToExport = _words.map((w) => Word(
          id: w['id'],
          word: w['word'],
          translation: w['translation'],
          pronunciation: w['pronunciation'],
          meaning: w['meaning'],
          example: w['example'],
          category: w['category'],
          difficulty: w['difficulty'] is int ? w['difficulty'] : int.tryParse(w['difficulty']?.toString() ?? '1') ?? 1,
          createdAt: w['createdAt'] != null ? DateTime.fromMillisecondsSinceEpoch(w['createdAt'] as int) : DateTime.now(),
        )).toList();
        
        // 导出单词到CSV文件
        final success = await WordImportExportUtil.exportWordsToCSV(wordsToExport);
        
        setState(() {
          _isLoading = false;
          _statusMessage = success != null ? '成功导出${wordsToExport.length}个单词' : '导出单词失败';
        });
      }
    } catch (e) {
      developer.log('导出单词失败: $e', error: e);
      setState(() {
        _isLoading = false;
        _statusMessage = '导出单词失败: $e';
      });
    }
  }

  // 导入单词
  Future<void> _importWords() async {
    try {
      setState(() {
        _isLoading = true;
        _statusMessage = '正在导入单词...';
      });
      
      // 从CSV或Excel文件导入单词
      final importResult = await WordImportExportUtil.importWordsFromCSVOrExcel();
      
      setState(() {
        _words = importResult.words.map<Map<String, dynamic>>((word) => word.toMap()).toList();
        _isLoading = false;
        if (importResult.hasErrors) {
          _statusMessage = '成功导入${importResult.words.length}个单词，但有${importResult.errors.length}个错误';
        } else {
          _statusMessage = '成功导入${importResult.words.length}个单词';
        }
      });
      
      // 询问用户是否要保存到数据库
      final shouldSave = await showDialog<bool>(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('保存到数据库', style: TextStyle(fontFamily: 'FangSong')),
          content: const Text('是否将导入的单词保存到数据库？', style: TextStyle(fontFamily: 'FangSong')),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(false),
              child: const Text('取消', style: TextStyle(fontFamily: 'FangSong')),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(true),
              child: const Text('确定', style: TextStyle(fontFamily: 'FangSong')),
            ),
          ],
        ),
      ) ?? false;
      
      if (shouldSave) {
        await _saveWordsToDatabase(_words);
      }
    } catch (e) {
      developer.log('导入单词失败: $e', error: e);
      setState(() {
        _isLoading = false;
        _statusMessage = '导入单词失败: $e';
      });
    }
  }

  // 保存单词到数据库
  Future<void> _saveWordsToDatabase(List<Map<String, dynamic>> wordMaps) async {
    try {
      setState(() {
        _statusMessage = '正在保存单词到数据库...';
      });
      
      final databaseService = DatabaseService();
      await databaseService.init();
      
      // 将Map转换为Word对象
      final List<Word> words = wordMaps.map<Word>((w) => Word(
        id: w['id'],
        word: w['word'],
        translation: w['translation'],
        pronunciation: w['pronunciation'],
        meaning: w['meaning'],
        example: w['example'],
        category: w['category'],
        difficulty: w['difficulty'] is int ? w['difficulty'] : int.tryParse(w['difficulty']?.toString() ?? '1') ?? 1,
        createdAt: w['createdAt'] != null ? DateTime.fromMillisecondsSinceEpoch(w['createdAt'] as int) : DateTime.now(),
      )).toList();
      
      // 批量保存单词到数据库
      final successCount = await databaseService.wordRepository.addWords(words);
      
      setState(() {
        _statusMessage = '成功保存${successCount}个单词到数据库';
      });
      
      // 保存成功后不自动返回列表页面，但设置刷新标志，让用户可以继续查看已创建的单词
      // 用户可以通过AppBar中的返回按钮手动返回，返回时会通知列表页面刷新
    } catch (e) {
      setState(() {
        _statusMessage = '保存单词到数据库失败: $e';
      });
      rethrow;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('单词导入导出', style: TextStyle(fontFamily: 'FangSong')),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            // 返回并通知列表页面刷新
            Navigator.pop(context, true);
          },
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.check),
            tooltip: '完成并返回',
            onPressed: () {
              // 返回并通知列表页面刷新
              Navigator.pop(context, true);
            },
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ElevatedButton(
              onPressed: _createSampleWords,
              child: const Text('创建示例单词', style: TextStyle(fontFamily: 'FangSong')),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _exportWords,
              child: const Text('导出单词', style: TextStyle(fontFamily: 'FangSong')),
            ),
            const Padding(
              padding: EdgeInsets.only(left: 16.0),
              child: Text('支持导出格式：CSV、Excel', 
                style: TextStyle(fontSize: 12, color: Colors.grey, fontFamily: 'FangSong')),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _importWords,
              child: const Text('导入单词', style: TextStyle(fontFamily: 'FangSong')),
            ),
            const Padding(
              padding: EdgeInsets.only(left: 16.0),
              child: Text('支持导入格式：CSV、Excel（包含读音、单词、释义、例句、分类等字段）', 
                style: TextStyle(fontSize: 12, color: Colors.grey, fontFamily: 'FangSong')),
            ),
            const SizedBox(height: 24),
            Text('状态: $_statusMessage',
                style: const TextStyle(fontWeight: FontWeight.bold, fontFamily: 'FangSong')),
            const SizedBox(height: 24),
            const Text('当前单词列表:',
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16, fontFamily: 'FangSong')),
            const SizedBox(height: 8),
            Expanded(
              child: _words.isEmpty
                  ? const Center(child: Text('暂无单词数据', style: TextStyle(fontFamily: 'FangSong')))
                  : ListView.builder(
                      itemCount: _words.length,
                      itemBuilder: (context, index) {
                        final word = _words[index];
                        return Card(
                          margin: const EdgeInsets.only(bottom: 8),
                          child: Padding(
                            padding: const EdgeInsets.all(12.0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  '${index + 1}. ${word['word']}',
                                  style: const TextStyle(fontWeight: FontWeight.bold, fontFamily: 'Arial'),
                                ),
                                const SizedBox(height: 8),
                                Text('发音: ${word['pronunciation']}', style: const TextStyle(fontFamily: 'Arial')),
                                Text('翻译: ${word['translation']}', style: const TextStyle(fontFamily: 'FangSong')),
                                Text('释义: ${word['meaning']}', style: const TextStyle(fontFamily: 'FangSong')),
                                Text('例句: ${word['example']}', style: const TextStyle(fontFamily: 'FangSong')),
                                const SizedBox(height: 4),
                                Text(
                                  '分类: ${word['category']} | 难度: ${word['difficulty']}',
                                  style: const TextStyle(fontSize: 12, color: Colors.grey, fontFamily: 'FangSong'),
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
            ),
          ],
        ),
      ),
    );
  }
}